import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../api/api_service.dart';
import '../../models/video.dart';
import '../../utils/app_icons.dart';
import '../../config/app_theme.dart';
import '../../providers/app_state.dart';
import 'video_detail_screen.dart';

class VideoScreen extends StatefulWidget {
  @override
  _VideoScreenState createState() => _VideoScreenState();
}

class _VideoScreenState extends State<VideoScreen> {
  final ApiService _apiService = ApiService();
  List<Video> _videos = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadVideos();
  }

  Future<void> _loadVideos() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final videos = await _apiService.getVideos(limit: 20);
      setState(() {
        _videos = videos;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      print('Error loading videos: $e');
    }
  }

  void _navigateToVideoDetail(Video video) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => VideoDetailScreen(video: video),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('宠物视频'),
        actions: [
          IconButton(
            icon: Image.asset(AppIcons.search, width: 24, height: 24, color: Colors.white),
            onPressed: () {
              // TODO: 实现视频搜索功能
            },
          ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadVideos,
              child: GridView.builder(
                padding: EdgeInsets.all(16.0),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 12.0,
                  mainAxisSpacing: 12.0,
                  childAspectRatio: 0.75,
                ),
                itemCount: _videos.length,
                itemBuilder: (context, index) {
                  final video = _videos[index];
                  return _buildVideoCard(video);
                },
              ),
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _showUploadDialog();
        },
        backgroundColor: AppTheme.primaryColor,
        child: Image.asset(AppIcons.add, width: 24, height: 24, color: Colors.white),
      ),
    );
  }

  Widget _buildVideoCard(Video video) {
    final appState = Provider.of<AppState>(context);
    final bool isLiked = appState.likedVideos.contains(video.id);
    
    return GestureDetector(
      onTap: () => _navigateToVideoDetail(video),
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
                  child: Image.network(
                    video.thumbnailUrl,
                    height: 120,
                    width: double.infinity,
                    fit: BoxFit.cover,
                  ),
                ),
                Positioned(
                  right: 8,
                  bottom: 8,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.6),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      '${video.views}次观看',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                      ),
                    ),
                  ),
                ),
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: Center(
                    child: Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.5),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.play_arrow,
                        color: Colors.white,
                        size: 24,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    video.title,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: AppTheme.bodyStyle,
                  ),
                  SizedBox(height: 8),
                  Row(
                    children: [
                      InkWell(
                        onTap: () {
                          appState.toggleLikeVideo(video.id);
                        },
                        child: Row(
                          children: [
                            Image.asset(
                              AppIcons.like,
                              width: 16,
                              height: 16,
                              color: isLiked ? AppTheme.primaryColor : AppTheme.secondaryTextColor,
                            ),
                            SizedBox(width: 4),
                            Text(
                              '${video.likes + (isLiked ? 1 : 0)}',
                              style: TextStyle(
                                fontSize: 12,
                                color: isLiked ? AppTheme.primaryColor : AppTheme.secondaryTextColor,
                              ),
                            ),
                          ],
                        ),
                      ),
                      SizedBox(width: 12),
                      Row(
                        children: [
                          Image.asset(
                            AppIcons.comment,
                            width: 16,
                            height: 16,
                            color: AppTheme.secondaryTextColor,
                          ),
                          SizedBox(width: 4),
                          Text(
                            '${video.comments}',
                            style: AppTheme.captionStyle,
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  void _showUploadDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('上传视频'),
          content: Text('即将添加上传视频功能，敬请期待！'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('关闭'),
            ),
          ],
        );
      },
    );
  }
} 